'use strict'

const {UserAnswer, Question} = require('../entity/myentity')

const {Service} = require('egg')

class userAnswerService extends Service {
  /**
   * @param {UserAnswer[]} userAnswerList 用户提交的答案列表
   * @param {number} e_id 考试编号
   */
  async commit(userAnswerList, e_id) {
    //console.log(userAnswerList)
    const {ctx, app} = this
    const conn = await app.mysql.beginTransaction();
    try {
      let u_id = userAnswerList[0].u_id;
      let grade = await conn.get("grade", {u_id: u_id, e_id: e_id});
      if (grade != null) {
        ctx.logger.error(`用户${u_id}重复提交考试${e_id}，拒绝插入数据`)
        await conn.rollback();
        return {suc: false, msg: "请勿重复提交！"}
      }
      for (let i in userAnswerList) {
        let ua = userAnswerList[i]
        await conn.insert("u_answer", {u_id: ua.u_id, q_id: ua.q_id, answer: ua.answer, e_id});
        //ctx.logger.info(`用户${u_id}为题目${userAnswerList[i].q_id}新建答案：${userAnswerList[i].answer}`)
      }
      //自动阅卷
      let pass = false
      let rightCount = 0;
      let questionCount = 0;
      /**
       * 查询当前考试全部题目
       * @type {ExamQuestion[]}
       */
      let allExamQuestion = await conn.select("e_question", {where: {e_id: e_id}})
      questionCount = allExamQuestion.length
      for (let i in allExamQuestion) {
        /**
         * 查询题目
         * @type {Question}
         */
        let q = await conn.get('question', {id: allExamQuestion[i].q_id})
        /**
         * 查询题目的正确答案
         * @type {QuestionAnswer[]}
         */
        let q_rightAnswer = await conn.select("q_answer", {where: {q_id: q.id, isRight: true}})
        /**@type{ExamQuestion}*/
        /**
         * 查询用户提交的答案
         * @type {UserAnswer[]}
         */
        let userAnswerList = await conn.select("u_answer", {where: {u_id: u_id, q_id: q.id, e_id}})
        //代表该题是否正确的状态值
        let question_right = true
        if (userAnswerList.length === q_rightAnswer.length) {
          //存储正确答案与考生提交答案的比对结果
          let rightFlag = []
          for (let i = 0; i < q_rightAnswer.length; i++) {
            rightFlag.push(false)
          }
          /*
            遍历正确答案列表，使其和考生提交的答案一一比对
            并将比对结果存储在rightFlag中
           */
          for (let i in q_rightAnswer) {
            for (let j in userAnswerList) {
              if (q_rightAnswer[i].answer === userAnswerList[j].answer) {
                rightFlag[i] = true
              }
            }
          }
          //遍历比对结果rightFlag，如果全为真，则设置question_right判定该题做对了
          for (let i in rightFlag) {
            if (!rightFlag[i]) {
              question_right = false;
              break;
            }
          }
        } else {
          //当考生提交的答案列表和正确答案列表长度不一致时，直接判断为错误
          question_right = false
        }
        //根据状态值使做对的题目计数增加
        if (question_right) {
          rightCount++
        }
      }
      //判定用户是否及格
      /**@type{Exam}*/
      let exam = await conn.get("exam", {id: e_id})
      let passScore = exam.pass_score / 100
      pass = (rightCount / questionCount) >= passScore
      //将user的这场考试标记为完成
      await conn.insert("grade", {
        u_id: u_id,
        e_id: e_id,
        pass: pass,
        teacherShow: true,
        userCommit: true,
        right_count: rightCount
      });
      ctx.logger.info(`用户${u_id}完成了考试${e_id}`)
      await conn.commit();
      return {suc: true, msg: "用户提交成功"}
    } catch (e) {
      await conn.rollback();
      ctx.logger.error(e)
      return {suc: false, msg: e}
    }
  }

  /**
   * 获取一些user答案
   * @param {UserAnswer} userAnswer
   * @returns {Promise<void>}
   */
  async get(userAnswer) {
    const {app} = this
    try {
      let query = await app.mysql.select("u_answer", {where: userAnswer});
      app.logger.info("查询一些userAnswer");
      return {suc: true, data: query, msg: "查询成功！"}
    } catch (e) {
      app.logger.error(e);
      return {suc: false, msg: e}
    }
  }


  async getUserAllAnswer(u_id, e_id) {
    const {app} = this
    const mysql = app.mysql
    try {
      let query = await mysql.select("u_answer", {where: {u_id, e_id}})
      app.logger.log(`查询用户${u_id}在考试${e_id}提交的全部答案`)
      return {suc: true, data: query, msg: "查询全部提交的答案成功"}
    } catch (e) {
      app.logger.error(e)
      return {suc: false, msg: e}
    }
  }


  async getUserQuestionAnswer(u_id, e_id, q_id) {
    const {app} = this
    const mysql = app.mysql
    try {
      let query = await mysql.select("u_answer", {where: {u_id, e_id, q_id}})
      app.logger.log(`查询用户${u_id}在考试${e_id}提交的题目${q_id}的全部答案`)
      return {suc: true, data: query, msg: "查询全部提交的答案成功"}
    } catch (e) {
      app.logger.error(e)
      return {suc: false, msg: e}
    }
  }

  /**
   * 判断用户在某场考试的某道题是否做对
   * @param {number} u_id 用户id
   * @param {number} e_id 考试id
   * @param {number} q_id 题目id
   */
  async userIsRight(u_id, e_id, q_id) {

    const {mysql, logger} = this.app
    try {
      /**
       * 查询题目
       * @type {Question}
       */
      let q = await mysql.get('question', {id: q_id})

      /**
       * 查询题目的正确答案
       * @type {QuestionAnswer[]}
       */
      let q_rightAnswer = await mysql.select("q_answer", {where: {q_id: q.id, isRight: true}})
      /**@type{ExamQuestion}*/
      /**
       * 查询用户提交的答案
       * @type {UserAnswer[]}
       */
      let userAnswerList = await mysql.select("u_answer", {where: {u_id: u_id, q_id: q.id, e_id}})
      //代表该题是否正确的状态值
      let question_right = true
      if (userAnswerList.length === q_rightAnswer.length) {
        //存储正确答案与考生提交答案的比对结果
        let rightFlag = []
        for (let i = 0; i < q_rightAnswer.length; i++) {
          rightFlag.push(false)
        }
        /*
          遍历正确答案列表，使其和考生提交的答案一一比对
          并将比对结果存储在rightFlag中
         */
        for (let i in q_rightAnswer) {
          for (let j in userAnswerList) {
            if (q_rightAnswer[i].answer === userAnswerList[j].answer) {
              rightFlag[i] = true
            }
          }
        }
        //遍历比对结果rightFlag，如果全为真，则设置question_right判定该题做对了
        for (let i in rightFlag) {
          if (!rightFlag[i]) {
            question_right = false;
            break;
          }
        }
      } else {
        //当考生提交的答案列表和正确答案列表长度不一致时，直接判断为错误
        question_right = false
      }
      logger.info(`判断用户${u_id}在考试${e_id}提交的题目${q_id}的对错，判断为${question_right}`)
      return {suc: true, data: question_right, msg: '查询成功'}
    } catch (e) {
      logger.error(e)
      return {suc: false, msg: e}
    }
  }
}

module.exports = userAnswerService
